#!/usr/bin/python

import argparse
import os
import tarfile
import tempfile

parser = argparse.ArgumentParser(description='Upload a directory to a server via ssh.')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
parser.add_argument('-v', '--verbose', action='store_true', default=False, dest='verbose', help='Give verbose output')
parser.add_argument('-s', '--source', action='store', default=os.getcwd(), dest='source', help='Source directory to archive')
parser.add_argument('-d', '--destination', action='store', dest='destination', help='Destination for the archive on the remote machine', required=True)
parser.add_argument('-c', '--connection-string', action='store', dest='connection', help='Connection string to use for connecting to the remote machine. E.g. "user@domain.com"', required=True)
parser.add_argument('-i', '--ignore', action='store', dest='ignore', help='Custom filenames to ignore')

args = parser.parse_args()
cwd = os.getcwd()
verbose = args.verbose
host = args.connection
destination = args.destination

if verbose:
    print("Chdir'ing to {}".format(args.source))

os.chdir(args.source)

bad_files = ['.svn', '.hg', '.git']
bad_files.extend(args.ignore.split(','))

def file_filter(name):
    for bad in bad_files:
        if bad in name:
            return True

    return False

filename = ''

if verbose:
    print('Creating temporary file...')

with tempfile.NamedTemporaryFile(delete=False, suffix='.tar') as _fileobj:
    filename = _fileobj.name

if verbose:
    print('Archiving directory...')

with tarfile.open(filename, mode='w:gz') as tar:
    for dirpath, dirnames, filenames in os.walk(os.getcwd()):
        for f in filenames:
            # we don't want the real path, just relative.
            directory = dirpath[len(cwd)+1:]
            tar.add(os.path.join(directory, f), exclude=file_filter)

size = os.path.getsize(filename)

if verbose:
    print('Uploading {} bytes with {}...'.format(size, host))

execute_string = 'cat {} | ssh {} tar xz -C {}'.format(filename, host, destination)

if verbose:
    print('executing {}'.format(execute_string))

os.system(execute_string)

if verbose:
    print('Removing temporary file...')

os.remove(filename)
